package com.ksd.quartz.util;

import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.util.ArrayList;
import java.util.List;

public class SystemTool {
	public static Object execFile(String osType, String cmd) {
		try {
			String[] cmdA = null;
			List<String> list = new ArrayList<>();
			if ("windows".equals(osType)) {
				Runtime.getRuntime().exec(cmd);
			} else {
				list.add("/bin/sh");
				list.add("-c");
				list.add(cmd);
				System.out.println("cmd: "+cmd);
			}
			cmdA = (String[]) list.toArray(new String[list.size()]);
			//解决脚本没有执行权限

			ProcessBuilder builder = new ProcessBuilder("/bin/chmod", "777",cmd);
			Process process = builder.start();
			process.waitFor();
			Process ps = Runtime.getRuntime().exec(cmdA);
			ps.waitFor();
			LineNumberReader br = new LineNumberReader(new InputStreamReader(ps.getInputStream()));
			StringBuffer sb = new StringBuffer();
			String line;
			while ((line = br.readLine()) != null) {
				System.out.println("line: "+line);
				sb.append(line).append("\n");
			}
			System.out.println("读取脚本的所有数据："+sb.toString());
			br.close();
			return sb.toString();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	
	public static Object execResult(String osType, String cmd) {
		try {
			String[] cmdA = null;
			List<String> list = new ArrayList<>();
			if ("windows".equals(osType)) {
				// list.add("C:\\Windows\\System32\\cmd.exe /c "+ cmd);
				Runtime.getRuntime().exec(cmd);
			} else {
				list.add("/bin/sh");
				list.add("-c");
				list.add(cmd);
				System.out.println("cmd: "+cmd);
			}
			cmdA = (String[]) list.toArray(new String[list.size()]);
			Process process = Runtime.getRuntime().exec(cmdA);
			LineNumberReader br = new LineNumberReader(new InputStreamReader(process.getInputStream()));
			StringBuffer sb = new StringBuffer();
			String line;
			while ((line = br.readLine()) != null) {
				System.out.println("line: "+line);
				sb.append(line).append("\n");
			}
			System.out.println(sb.toString());
			return sb.toString();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	 
}
